using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

using WXWorkSvc.Common.Data;

namespace OpenPms.Areas.D.Pages.Setup.WXMsg;

public class EditModel : PageModel
{
    private readonly AppDbContext db;
    private readonly WXDbContext wxdb;
    public EditModel(AppDbContext db, WXDbContext wxdb)
    {
        this.db = db;
        this.wxdb = wxdb;
    }
    [BindProperty]
    public EWXMsgType WXMsgType { get; set; } = default!;
    [BindProperty]
    public List<TUser> Items { get; set; } = default!;
    public TUser Item { get; set; } = default!;
    public async Task OnGetAsync(EWXMsgType wxMsgType)
    {
        WXMsgType = wxMsgType;
        //WXMsgType =Enum.Parse<EWXMsgType>(msgType);
        Items = await wxdb.Users.Where(ii => ii.CorpId == User.GetCorpId()).ToListAsync();
        var rec = await db.WXMsgs.Where(ii => ii.HotelId == User.GetExtId() && ii.WXMsgType == WXMsgType).FirstAsync();
        if (!string.IsNullOrEmpty(rec.UserIds))
        {
            var userIds = rec.UserIds.Split('|');
            foreach (var item in Items.Where(ii => userIds.Contains(ii.UserId)))
            {
                item.IsReceive = true;
            }
        }
        Items=Items.OrderByDescending(ii=>ii.IsReceive).ThenBy(ii=>ii.UserId).ToList();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        var userIds = Items.Where(ii => ii.IsReceive).Select(ii => ii.UserId).ToList();
        var strUserIds = string.Join("|", userIds);
        await db.WXMsgs.Where(ii => ii.HotelId == User.GetExtId() && ii.WXMsgType == WXMsgType).ExecuteUpdateAsync(ii => ii.SetProperty(jj => jj.UserIds, strUserIds));
        return RedirectToPage("./Index");
    }
}
